// 建议放在 config 子包下，例如 com.itheima.springboottest.config
package com.itheima.springboottest;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // ---- 下面是完整的实现，替换你原来的注释和 return 语句 ----

        // 1. 创建 RedisTemplate 对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 2. 创建序列化工具
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        // 配置 Jackson ObjectMapper
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSerializer.setObjectMapper(om);

        // 3. 设置 Key 和 Value 的序列化规则
        // Key 采用 String 的序列化方式
        template.setKeySerializer(stringSerializer);
        // Hash 的 Key 也采用 String 的序列化方式
        template.setHashKeySerializer(stringSerializer);

        // Value 序列化方式采用 Jackson
        template.setValueSerializer(jacksonSerializer);
        // Hash的 Value 序列化方式采用 Jackson
        template.setHashValueSerializer(jacksonSerializer);

        template.afterPropertiesSet();

        // 4. 返回配置好的 RedisTemplate 对象
        return template;
    }
}
